from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn

from app.api.router import api_router
from app.core.config import settings
from app.modules.gomoku.module import init_module as init_gomoku_module
from app.modules.auth.module import init_module as init_auth_module
from app.modules.crawler import CrawlerModule

app = FastAPI(
    title=settings.PROJECT_NAME, 
    openapi_url=f"{settings.API_V1_STR}/openapi.json",
    version="0.1.0",
)

# 设置CORS
if settings.BACKEND_CORS_ORIGINS:
    app.add_middleware(
        CORSMiddleware,
        allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

# 包含API路由
app.include_router(api_router, prefix=settings.API_V1_STR)

# 初始化认证模块（必须在其他模块之前初始化，因为其他模块可能依赖认证）
init_auth_module(app)

# 初始化五子棋模块
init_gomoku_module(app)

# 初始化爬虫模块
crawler_module = CrawlerModule()
crawler_module.register_routes(app, prefix=f"{settings.API_V1_STR}/crawler")

@app.get("/")
async def root():
    return {"message": "Welcome to Python Backend Service"}

if __name__ == "__main__":
    uvicorn.run("app.main:app", host="0.0.0.0", port=8000, reload=True) 